<?php
App::import('Component', 'BAuth');

class LocalAuthComponent extends BAuthComponent {

  function initialize(&$controller) {
    parent::initialize($controller);
    $this->authModel = 'LocalAccount';
  }

  function login($data) {
    if (isset($data['LocalAccount']['crypted_password'])) {
      $password = "'" . $data['LocalAccount']['crypted_password'] . "'";
    }
    else
    if (isset($data['LocalAccount']['password'])) {
      $password = "PASSWORD('" . addslashes($data['LocalAccount']['password']) . "')";
    }
    else {
      return FALSE;
    }
    
    // just saying $uses = array('LocalAccount') does not work
    $model = ClassRegistry::getObject('LocalAccount');
    
    $account = $model->find('first', array(
      'conditions' => array(
        'LocalAccount.username' => $data['LocalAccount']['username'],
        "LocalAccount.crypted_password = {$password}",
       ),
       'fields' => array('LocalAccount.id', 'LocalAccount.user_id', 'LocalAccount.username')));
    
    $prev_account = $this->user();
    if ($prev_account) {
      $user_id = $model->User->user_id($prev_account);
      $this->logout();
    }

    if (isset($user_id) && $user_id && $user_id != $account['LocalAccount']['user_id']) {
      $model->User->merge_users($user_id, $account['LocalAccount']['user_id']);
      $message = "Dein Profil {$user_id} wurde in das neue Profil {$account['LocalAccount']['user_id']} übernommen.\n";
    }

    return parent::login($account);
  }
  
  function password($password) {
    $model = ClassRegistry::getObject('LocalAccount');
    return $model->field("PASSWORD('" . addslashes($password) . "')");
  }
}